import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';

import '../const.dart';

class MyDio {
  static final String GET = "GET";
  static final String POST = "POST";
  static final String CODE = "code";
  static var codes = {200};

  Dio dio = Dio();
  static MyDio _instance;

  static MyDio getInstance({String url, String token}) {
    if (_instance == null) {
      _instance = MyDio(url: url, token: token);
    }
    return _instance;
  }

  MyDio({String url, String token}) {
    var baseUrl;
    url == null ? baseUrl = Const.BASEURL : baseUrl = url;

    dio.options.headers = {
      "Authorization": 'Bearer $token',
    };
    dio.options.baseUrl = baseUrl;
    dio.options.connectTimeout = 5000;
    dio.options.receiveTimeout = 3000;
    dio.options.responseType = ResponseType.plain;

//    dio = Dio(BaseOptions(
//      baseUrl: baseUrl,
//      headers: {HttpHeaders.contentTypeHeader: 'application/json'},
//      connectTimeout: 15000,
//      receiveTimeout: 15000,
//      responseType: ResponseType.plain,
//    ));
  }

  clearInstance() {
    _instance = null;
  }

  //get请求
  get(String url, Function successCallBack,
      {params, Function errorCallBack}) async {
    _requstHttp(url, successCallBack, GET, params, errorCallBack);
  }

  //post请求
  post(String url, Function successCallBack,
      {params, Function errorCallBack}) async {
    _requstHttp(url, successCallBack, POST, params, errorCallBack);
  }

  _requstHttp(String url, Function successCallBack,
      [String method,
      Map<String, dynamic> params,
      Function errorCallBack]) async {
    String errorMsg = '';
    int code;
    try {
      Response response;
//      _addStartHttpInterceptor(dio); //添加请求之前的拦截器
      if (method == GET) {
        if (params != null && params.isNotEmpty) {
          var headers = Map<String, String>();
          headers[HttpHeaders.contentTypeHeader] = 'application/json';
          Options options = Options(
            headers: headers,
          );
          response =
              await dio.get(url, queryParameters: params, options: options);
        } else {
          response = await dio.get(url);
        }
      } else if (method == POST) {
        if (params != null && params.isNotEmpty) {
          var headers = Map<String, String>();
          headers[HttpHeaders.contentTypeHeader] = 'application/json';
          Options options = Options(
            headers: headers,
          );
          response = await dio.post(
            url,
            data: params,
            options: options,
          );
        } else {
          response = await dio.post(url);
        }
      }
      print('HttpResponse$response');
      Map<String, dynamic> dataMap = json.decode(response.toString());
      if (successCallBack != null) {
        successCallBack(dataMap);
      }
    } on DioError catch (error) {
      Response errorResponse;
      if (error.response != null) {
        errorResponse = error.response;
      } else {
        errorResponse = new Response(statusCode: 666);
      }

      // 超时
      if (error.type == DioErrorType.CONNECT_TIMEOUT) {
        errorResponse.statusCode = 999;
      }
      // debug模式才打印
//      if (YYConfig.DEBUG) {
//        print('请求异常: ' + error.toString());
//        print('请求异常url: ' + url);
//        print('请求头: ' + option.headers.toString());
//        print('method: ' + option.method);
//      }
      // 返回错误信息
      _error(errorCallBack, errorResponse.statusCode);
    }
  }

  _error(Function errorCallBack, int code) {
    if (errorCallBack != null) {
      errorCallBack(code);
    }
  }

//  _addStartHttpInterceptor(Dio dio) {
//    dio.interceptor.request.onSend = (Options options) {
//      // 在请求被发送之前做一些事情   比如加密的一些操作 或者添加token等参数 对head 或者请求参数进行加工处理
//      Map<String, dynamic> headers = options.headers;
//      Map<String, dynamic> body = options.data;
//      /*request['token'] = '1111111111';
//      headers['addParam'] = 'aaaaaaaaaaaaaaa';*/
//      return options;
//    };
//  }
}
